package com.yin.unsafe;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;


/**
 * java.util.ConcurrentModificationException  并发修改异常!
 */
public class ListTest {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("1", "2", "3");
        list.forEach(System.out::println);


        // 并发下ArrayList不安全
        /**
         * 解决方案
         * 1.  List<String> arrayList = new Vector<>();
         * 2.  List<String> arrayList = Collections.synchronizedList(new ArrayList<>());
         * 3.  List<String> arrayList = new CopyOnWriteArrayList<>();
         */
        List<String> arrayList = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                arrayList.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(arrayList);
            },String.valueOf(i)).start();
        }
    }
}
